#include <memmonitor.h>
#include <fstream>
#include <sstream>
#include <string>
#include <cinttypes>

MemMonitor::MemMonitor()
{

}

double MemMonitor::getMemUsage()
{
    std::ifstream file("/proc/meminfo");
    std::string line;
    uint64_t memTotal = 0;
    uint64_t memAvailable = 0;

    while (std::getline(file, line))
    {
        if (line.find("MemTotal") == 0) {
            sscanf(line.c_str(), "MemTotal: %" SCNu64, &memTotal);
        } else if (line.find("MemAvailable") == 0) {
            sscanf(line.c_str(), "MemAvailable: %" SCNu64, &memAvailable);
        }

        // 提前退出循环，如果已经找到所需的值
        if (memTotal != 0 && memAvailable != 0) {
            break;
        }
    }

    uint64_t used = memTotal - memAvailable;
    return (100.0 * used) / memTotal;

}
